package com.zhuiyi.yiqingbackend.service.impl;

import com.zhuiyi.yiqingbackend.common.ErrorCode;
import com.zhuiyi.yiqingbackend.domain.Base;
import com.zhuiyi.yiqingbackend.domain.Person;
import com.zhuiyi.yiqingbackend.exception.BusinessException;
import com.zhuiyi.yiqingbackend.mapper.PersonMapper;
import com.zhuiyi.yiqingbackend.service.BaseService;
import com.zhuiyi.yiqingbackend.service.PersonService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
public class PersonServiceImpl implements PersonService {

    @Resource
    private PersonMapper personMapper;
    @Resource
    private BaseService baseService;
    @Override
    public List<Person> getAllPerson() {
        List<Person> allPerson = personMapper.getAllPerson();
        if(allPerson.size()>0){
            return allPerson;
        }
        throw new BusinessException(ErrorCode.FAIL, "查询失败");
    }

    @Override
    public boolean insertPerson(Person person) {
        //成员变量 没赋值，在创建时自动赋该类型的默认值 int 默认为0
        String phone = person.getPhone();
        Base base = baseService.getBaseByPhone(phone);
        if(base == null){
            return personMapper.insertPerson(person);
        }else {
            int baseId = base.getId();
            person.setBaseid(baseId);
            return personMapper.insertPerson(person);
        }
    }

    @Override
    public boolean deletePerson(int id) {
        Person person = personMapper.getPersonById(id);
        if(person==null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "用户不存在");    //id不存在
        }
        boolean result = personMapper.deletePerson(id);
        if(!result){
            throw new BusinessException(ErrorCode.DELETE_FAIL);
        }
        return result;
    }

    @Override
    public boolean updatePerson(Person person) {
        Person person1 = personMapper.getPersonById(person.getId());
        if(person1==null) {
            throw new BusinessException(ErrorCode.UPDATE_FAIL);
        }
        boolean result = personMapper.updatePerson(person);
        if(!result){
            throw new BusinessException(ErrorCode.UPDATE_FAIL);
        }
        return result;
    }

    @Override
    public List<Person> getPersonById(int id) {
        Person person = personMapper.getPersonById(id);
        if(person==null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "用户不存在");    //id不存在
        }
        List<Person> list  = new ArrayList<>();
        list.add(person);
        return list;
    }
}
